package org.example.controller;

import org.example.pojo.Couplename;
import org.example.pojo.User;
import org.example.service.CouplenameService;
import org.example.service.UserService;
import org.example.utils.Result;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/Couplename")
@Validated
public class CouplenameController {

    @Autowired
    private CouplenameService couplenameService;

    @Autowired
    private UserService userService;


    //关系绑定
    @PostMapping("/addrelation")
    public Result addrelation(@Validated String nickname,@Validated String timeTogether) {
        //在user表单中查询对方是否注册
        User byNickname = userService.findByNickname(nickname);

        //获取到自己的id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        //从couplename表单中查询是否已有绑定关系
        String byId = couplenameService.findById(id);
        if (byNickname == null) {
            //对方还未注册
            return Result.error("您的对象还没有注册该应用，请注册后再绑定吧");
        } else {
            //对方已经注册
            if (byId == null) {
                //没有绑定关系
                //通过findById查询对方id
                Integer objectId = byNickname.getId();

                //查询对方是否有绑定关系
                String a = couplenameService.findById(objectId);

                if (a == null) {
                    couplenameService.add(id, objectId, timeTogether);

                    return Result.success("关系绑定成功");

                } else {
                    //对方已有绑定关系
                    return Result.error("对方已有绑定关系，请确认后重试");
                }
            } else {
                //有绑定关系
                return Result.error("关系一经过绑定，禁止修改");
            }
        }
    }

    //查询关系绑定信息
    @GetMapping("/relationDetails")
    public Result<User> relationDetails() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        //同过个人id查询对方
        Couplename couplename = couplenameService.relationDetails(id);

        //对比id对比要输出的是哪个
        if (id == couplename.getUser1Id()) {
            //如果id等于User1Id，则输出User2
            return Result.success(userService.findByUser(couplename.getUser2Id()));
        }
        //反之，则输出User2
        return Result.success(userService.findByUser(couplename.getUser1Id()));

    }

    @GetMapping("/getTime")
    public Result getTime() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");

        return Result.success(couplenameService.getTime(id));

    }

}
